package ntd.util.frame.storage.service;

import ntd.util.frame.storage.NtdStorage;
import ntd.util.frame.storage.bo.StorageInBO;
import ntd.util.frame.storage.bo.StorageOutBO;
import ntd.util.frame.storage.context.StorageContext;
import ntd.util.UtilCatch;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class NtdStorageService {

    public String generateUrl(StorageInBO storageInBO) {
        StorageContext storageContext = StorageContext.init(storageInBO);
        return storageContext.getNtdStorage().generateUrl(storageInBO.getBucketName(), storageInBO.getFileKey());
    }

    public StorageOutBO store(StorageInBO storage) {
        StorageContext storageContext = StorageContext.init(storage);

        NtdStorage ntdStorage = storageContext.getNtdStorage();

        ntdStorage.store(
                storage.getBucketName(),
                storage.getBytes(),
                storageContext.getNewFileName()
        );

        String url = ntdStorage.generateUrl(storage.getBucketName(), storageContext.getNewFileName());

        return new StorageOutBO(storageContext.getNewFileName(), appendFileName(storage.getOriginName(), url));
    }

    private String appendFileName(String fileName, String url) {
        return url + "?name=" + fileName;
    }

    public InputStream getFile(StorageInBO storageInBO) {
        StorageContext storageContext = StorageContext.init(storageInBO);
        NtdStorage ntdStorage = storageContext.getNtdStorage();
        InputStream inputStream = ntdStorage.loadInputStream(storageInBO.getBucketName(), storageInBO.getFileKey());
        return inputStream;
    }
}
